package com.ruoyi.orderParent.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.order.Utils.OrderUtils;
import com.ruoyi.order.domain.SysOrderOne;
import com.ruoyi.orderParent.domain.*;
import com.ruoyi.packages.domain.SysPackage;
import com.ruoyi.packages.mapper.SysPackageMapper;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.orderParent.service.ISysOrderParentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 批量订单Controller
 *
 * @author ruoyi
 * @date 2024-06-24
 */
@RestController
@RequestMapping("/orderParent/orderParent")
public class SysOrderParentController extends BaseController
{
    @Autowired
    private ISysOrderParentService sysOrderParentService;

    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysPackageMapper packageMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysStoreMapper sysStoreMapper;


    /**
     * 查询批量订单列表
     */
    @PreAuthorize("@ss.hasPermi('orderParent:orderParent:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysOrderParent sysOrderParent,
                              @RequestParam(name = "params[beginCreateTime]", required = false) Date beginCreateTime,
                              @RequestParam(name = "params[endCreateTime]", required = false) Date endCreateTime)
    {//判断应该返回哪些订单，如果为商户，则只返回自己dept下的背调订单，如果为代理商，则返回自己下所有的dept

        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String type = sysDept.getType();
        List<SysOrderParent> list=null;
        if (beginCreateTime!=null) {

            sysOrderParent.setBeginCreateTime(beginCreateTime);

        }

        if (endCreateTime!=null) {

            sysOrderParent.setEndCreateTime(endCreateTime);

        }


        //套餐信息封装
        if (sysOrderParent.getPackageType()!=null) {
            List<Long> packageIdss =packageMapper.selectSysPackageByOnline(sysOrderParent.getPackageType());
            sysOrderParent.setPackageList(packageIdss);
        }


        if (type.equals("2")) {
            //说明是商户查
            sysOrderParent.setDeptId(deptId);

            startPage();
            list = sysOrderParentService.selectSysOrderParentList(sysOrderParent);

        }
        else if (type.equals("1")) {
            //说明是代理商查
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            SysAgent sysAgent = agents.get(0);

            startPage();
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(sysAgent.getId());

            if (CollectionUtils.isEmpty(sysStores)) {
                return getDataTable(sysStores);
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            sysOrderParent.setDeptIds(storeDeptIds);
            list = sysOrderParentService.selectSysOrderParentList(sysOrderParent);

        }
        else if (type.equals("0")) {
            //说明是管理员
            List<SysStore> sysStores = sysStoreMapper.selectSysStoreByAgentId(0l);

            if (CollectionUtils.isEmpty(sysStores)) {
                return getDataTable(sysStores);
            }

            List<Long> storeDeptIds = sysStores.stream().map(SysStore::getDeptId).collect(Collectors.toList());

            sysOrderParent.setDeptIds(storeDeptIds);

            startPage();
            list = sysOrderParentService.selectSysOrderParentList(sysOrderParent);

        }



        if (CollectionUtils.isEmpty(list)) {
            return getDataTable(list);
        }
        //封装代理商名称
//        List<Long> agentIds = list.stream().map(SysOrderParent::getAgentId).collect(Collectors.toList());
//        List<SysAgent> agents = agentMapper.selectSysAgentByIds(agentIds);
//        Map<Long, String> agentMap = agents.stream().collect(Collectors.toMap(SysAgent::getId, c -> c.getName()));
        //封装套餐类型
        Set<Long> packageIds = list.stream().map(SysOrderParent::getSetmealId).collect(Collectors.toSet());
        ArrayList<Long> longs = new ArrayList<>(packageIds);
        List<SysPackage> packages = packageMapper.selectSysPackageByIds(longs);
        Map<Long, BigDecimal> packageAmountMap = packages.stream().collect(Collectors.toMap(SysPackage::getId, c -> c.getPrice()));

        Map<Long, String> packageLineMap = packages.stream().collect(Collectors.toMap(SysPackage::getId, c -> c.getLineStatus()));

        Set<Long> collect = list.stream().map(SysOrderParent::getUserId).collect(Collectors.toSet());
        List<Long> userIds = new ArrayList<>(collect);
        List<SysUser> users=userMapper.selectByIds(userIds);
        Map<Long, String> userMap = users.stream().collect(Collectors.toMap(SysUser::getUserId, c -> c.getUserName()));


        for (SysOrderParent orderOne : list) {
//            if (orderOne.getAgentId()==0) {
//                orderOne.setAgentName("——————");
//            }else {
//                orderOne.setAgentName(agentMap.get(orderOne.getAgentId()));
//            }

            orderOne.setOneAmount(packageAmountMap.get(orderOne.getSetmealId()));
            orderOne.setPackageType(packageLineMap.get(orderOne.getSetmealId()));
            orderOne.setUserName(userMap.get(orderOne.getUserId()));
        }



        return getDataTable(list);
    }

    /**
     * 导出批量订单列表
     */
    @PreAuthorize("@ss.hasPermi('orderParent:orderParent:export')")
    @Log(title = "批量订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOrderParent sysOrderParent)
    {
        List<SysOrderParent> list = sysOrderParentService.selectSysOrderParentList(sysOrderParent);
        ExcelUtil<SysOrderParent> util = new ExcelUtil<SysOrderParent>(SysOrderParent.class);
        util.exportExcel(response, list, "批量订单数据");
    }

    /**
     * 获取批量订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('orderParent:orderParent:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysOrderParentService.selectSysOrderParentById(id));
    }

    /**
     * 新增批量订单
     */
    @PreAuthorize("@ss.hasPermi('orderParent:orderParent:add')")
    @Log(title = "批量订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysOrderParent sysOrderParent)
    {
        return toAjax(sysOrderParentService.insertSysOrderParent(sysOrderParent));
    }

    /**
     * 修改批量订单
     */
    @PreAuthorize("@ss.hasPermi('orderParent:orderParent:edit')")
    @Log(title = "批量订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysOrderParent sysOrderParent)
    {
        return toAjax(sysOrderParentService.updateSysOrderParent(sysOrderParent));
    }

    /**
     * 删除批量订单
     */
    @PreAuthorize("@ss.hasPermi('orderParent:orderParent:remove')")
    @Log(title = "批量订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysOrderParentService.deleteSysOrderParentByIds(ids));
    }

    /**
     * 批量详情
     * @param id
     * @return
     */
    @GetMapping(value = "/detail/{id}")
    public AjaxResult getInfoDetail(@PathVariable("id") Long id)
    {
        Map<String,List<SysOrderDetail>> map = new HashMap<>();
        List<SysOrderDetail> list = sysOrderParentService.getSysOrderParentById(id);
        map.put("list",list);

        return success(map);
    }
    @Anonymous
    @PostMapping("/getOrderDetail/{id}")
    public AjaxResult getOrderDetail(@RequestBody OrderDetail orderDetail, @PathVariable("id") Long id){
        Map<String,List<SysOrderDetail>> map = new HashMap<>();
        List<SysOrderDetail> list = sysOrderParentService.getSysOrderDetail(orderDetail,id);
        for (SysOrderDetail orderOnes : list) {
            orderOnes.setIdNumber(OrderUtils.maskIDCard(orderOnes.getIdNumber()));

        }
        map.put("list",list);
        return success(map);
    }

}
